import config from '/api/config.js'
// 文件上传
export function upload(filePath, extra) {
  return new Promise((reslove, reject) => {
    uni.uploadFile({
      url: `${config.base_url}/common/upload`, // 开发者服务器地址，此 url 仅为示例
      name: 'file',
      filePath: filePath,
      formData: {
        extra: extra
      },
      success: res => {
        console.log('上传成功', res);
        if (res.statusCode === 200) {
          const result = JSON.parse(res.data)
          if (result.code === 200) {
            if (result.data.url) {
              reslove(result.data.url)
            } else {
              reject('签字图片异常')
            }
          } else {
            reject(result.msg)
          }
        } else {
          console.error('上传失败: ', res);
          reject(res)

        }
      },
      fail: error => {
        reject(error)
        console.error('上传失败: ', JSON.stringify(error));
      },
    });
  })

}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
// js 分转换成元
export const regFenToYuan = (fen) => {
  var num = fen;
  num = fen * 0.01;
  num += '';
  var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num = num.replace(reg, '$1');
  console.log(num, 'nnn');
  num = toDecimal2(num)
  return num
};
const toDecimal2 = (x) => {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}
// 节流
export function throttle(func, delay) {
  let timer = null; // 定义计时器变量
  return function () {
    const context = this; // 保存this指向
    if (!timer) {
      func.apply(context); // 第一次调用立即执行
      timer = setTimeout(() => {
        clearTimeout(timer); // 清除计时器
        timer = null; // 重置计时器为null
      }, delay);
    }
  };
}

export const ageCheck = function (iIdNo) {
  let tmpStr = '' // 首先声明了一个变量来接收身份证上的出生日期
  if (iIdNo.length == 15) { // 如果身份证位
    tmpStr = iIdNo.substring(6, 12)
    tmpStr = '19' + tmpStr // 十五位身份证 需要获取到年加  19
    tmpStr = tmpStr.substring(0, 4) + '-' + tmpStr.substring(4, 6) + '-' + tmpStr.substring(6)
  } else {
    tmpStr = iIdNo.substring(6, 14)
    tmpStr = tmpStr.substring(0, 4) + '-' + tmpStr.substring(4, 6) + '-' + tmpStr.substring(6)
  }

  let nian = parseInt(tmpStr.substring(0, 4)) // 获取到出生的年
  let yuefen = parseInt(tmpStr.substring(5, 7)) // 获取到身份证的月分
  let riqi = parseInt(tmpStr.substring(8, 10))
  // var date = "";//今天的日期

  let year = new Date().getFullYear()
  let yue = new Date().getUTCMonth() + 1 // 拿到今天的月份
  let ri = new Date().getDate()
  if (year > nian + 22 && year < nian + 75) {
    return true
  }
  if (year == nian + 22) {

    if (yuefen < yue) {
      return true
    } else {
      if (yuefen == yue) {
        if (ri < riqi) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    }
  }
  if (year == nian + 75) {
    if (yuefen > yue) {
      return true
    } else {
      if (yuefen == yue) {
        if (riqi < ri) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    }
  }
  return false
}
// 判断数据有几位小数
export function countDecimals(num) {
  var str = '' + num;
  if (str.indexOf('.') !== -1) {
    return str.length - str.indexOf('.') - 1;
  }
  return 0;
}
/**
 * 10000 => "10,000"
 * @param {number} num
 */
export function toThousandFilter(strNum) {
  return strNum.replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}